
import { baseUrl } from '@/common/config'
// 请求拦截器
uni.addInterceptor('request', {
  // 拦截前触发
  invoke(config) {
		const url = config.url
		if(!url.startsWith('https') || !url.startsWith('http')){
			config.url = baseUrl + config.url
		}
  }

})

let unauthorized = false

/**
 * http请求方法
 * 简单封装 uni.request 接口，使之返回 Promise 对象；
 * 请求类型默认POST
 * @param {Object} options 参考：https://uniapp.dcloud.net.cn/api/request/request.html
 */
export const request = async (options = {}) => {
	const access_token = uni.getStorageSync('access_token')
	let header = {
		'Content-Type': 'application/json',
		'x-device': 'wx_miniprogram'
	}

	if (access_token) {
		header['Authorization'] = 'Bearer ' + access_token
	}
	if (options.header) {
		header = {
			...header,
			...options.header
		}
	}

	return new Promise((resolve, reject) => {
		uni.request({
			method: 'POST',
			success(res) {
				const {
					datas,
					respCode,
					respMsg
				} = res.data || {}
				//对于后端数据没有datas的格式，单独处理
				if (res.data.hasOwnProperty("data")) {
					resolve(res.data)
					return
				}
				if (respCode === 200) {
					unauthorized = false
					resolve(res.data)
				} else {
					if (respCode === 401 && !unauthorized) {
						unauthorized = true
						// 未登录或登录过期
						uni.redirectTo({
							url: '/authPack/login/wxLogin'
							// url: '/authPack/login/phoneLogin'
						})
					}
					reject(res.data)
				}
			},
			fail: (err) => {
				reject(err)
			},
			...options,
			header,
		})
	})
}

export default request